package com.matrix.admin.open.test.service.impl;

import com.matrix.admin.open.test.service.IApachePoiTestService;
import com.matrix.common.dto.poi.test.UserPoiTest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liuweizhong
 * @since 2025-09-11 08:51
 */
@Slf4j
@Service
public class ApachePoiTestServiceImpl implements IApachePoiTestService {

    @Override
    public void exportExcel(HttpServletResponse response) {
        // 1. 设置HTTP响应头，告诉浏览器这是一个需要下载的文件
        try {
            // a. 设置内容类型 (MIME Type)
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());

            // b. 设置文件名，并进行URL编码，以防止中文乱码
            String fileName = "用户信息.xlsx";
//            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        } catch (Exception e) {
            // 处理设置响应头时的异常
            log.error("========[设置响应头时的异常]========: {}", e.getMessage());
        }

        // 2. 准备数据集 (在真实应用中，这部分数据应该从 Service 层获取)
        List<UserPoiTest> userList = new ArrayList<>();
        userList.add(new UserPoiTest(1, "张三", "zhangsan@example.com", LocalDate.of(1990, 5, 15)));
        userList.add(new UserPoiTest(2, "李四", "lisi@example.com", LocalDate.of(1988, 8, 22)));
        userList.add(new UserPoiTest(3, "王五", "wangwu@example.com", LocalDate.of(1995, 1, 30)));

        // === Apache POI 核心代码 ===
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("用户信息");

            // 定义表头
            String[] headers = {"ID", "姓名", "邮箱", "出生日期"};

            // ... (创建表头、样式、填充数据的代码与Servlet版本完全一样) ...
            // 为了简洁，这里省略了相同的代码，您可以直接从上面的Servlet示例中复制过来
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            CellStyle headerCellStyle = workbook.createCellStyle();
            headerCellStyle.setFont(headerFont);

            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerCellStyle);
            }

            CellStyle dateCellStyle = workbook.createCellStyle();
            CreationHelper createHelper = workbook.getCreationHelper();
            dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd"));

            int rowNum = 1;
            for (UserPoiTest user : userList) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(user.getId());
                row.createCell(1).setCellValue(user.getName());
                row.createCell(2).setCellValue(user.getEmail());
                Cell dateCell = row.createCell(3);
                dateCell.setCellValue(user.getBirthday());
                dateCell.setCellStyle(dateCellStyle);
            }

            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 3. 将工作簿写入响应的输出流
            try (OutputStream out = response.getOutputStream()) {
                workbook.write(out);
                out.flush(); // 确保所有数据都被写出
            }

        } catch (IOException e) {
            log.error("========[写入响应流时的异常]========: {}", e.getMessage());
        }
    }


    private void exportExcelTest(HttpServletResponse response) {

    }


    @Override
    public void exportWord(HttpServletResponse response) {
        
    }
}
